package com.icinfo.cloud.provider.common.utils;

import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.provider.common.constant.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 描述：统一社会信用代码工具类
 *
 * @Desc 描述
 * @Author mahan
 * @Date 2023/2/24
 */
public class SocialCreditCodeUtil {

	private static final String  REGEX = "^([1-9NY]{1})([1-9]{1})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9ABCDEFGHJKLMNPQRTUWXY])$";
	private static final String BASE_CODE_STRING = "0123456789ABCDEFGHJKLMNPQRTUWXY";
	private static final char[] BASE_CODE_ARRAY = BASE_CODE_STRING.toCharArray();
	private static final List<Character> BASE_CODES = new ArrayList<>();
	private static final String BASE_CODE_REGEX = "[" + BASE_CODE_STRING + "]{18}";
	private static final int[] WEIGHT = {1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28};
	private static final String OTHER_ORGANIZATION_REGEX = "[\\u4e00-\\u9fa5a-zA-Z0-9\\W_]*";

	static {
		for (char c : BASE_CODE_ARRAY) {
			BASE_CODES.add(c);
		}
	}

	/**
	 * 是否是有效的统一社会信用代码
	 *
	 * @param socialCreditCode 统一社会信用代码
	 * @return boolean
	 * @author shishengyao
	 * @date 2023/05/17
	 */
	public static boolean isValidSocialCreditCode(String socialCreditCode) {
		if (StrUtil.isBlank(socialCreditCode) || !Pattern.matches(BASE_CODE_REGEX, socialCreditCode)) {
			return false;
		}
		//正则校验统一社会信用代码
		if (!socialCreditCode.matches(REGEX)){
			return false;
		}
		char[] businessCodeArray = socialCreditCode.toCharArray();
		char check = businessCodeArray[17];
		int sum = 0;
		for (int i = 0; i < 17; i++) {
			char key = businessCodeArray[i];
			sum += (BASE_CODES.indexOf(key) * WEIGHT[i]);
		}
		int value = 31 - sum % 31;
		return check == BASE_CODE_ARRAY[value % 31];
	}

	/**
	 * 描述：是否是有效的单位编码
	 *
	 * @param socialCreditCode 统一社会信用代码
	 * @param entType          ent类型
	 * @return boolean
	 * @author shishengyao
	 * @date 2023/04/21
	 */
	public static boolean isValidEntCode(String socialCreditCode,String entType) {
		return isValidOtherOrganizationCode(socialCreditCode,entType) || isValidSocialCreditCode(socialCreditCode);

	}

	/**
	 * 描述：是否是有效的其他组织机构代码校验
	 *
	 * @param socialCreditCode 统一社会信用代码
	 * @param entType          ent类型
	 * @return boolean
	 * @author shishengyao
	 * @date 2023/05/17
	 */
	public static boolean isValidOtherOrganizationCode(String socialCreditCode,String entType) {
		if (StrUtil.isBlank(socialCreditCode)  || StrUtil.isBlank(entType) || !Constant.STRING_3.equals(entType) ) {
			return false;
		}
		// 其他组织机构 代码校验规则：18、16、20、12 位的包含数字或字母的字符串
		int length=socialCreditCode.length();
		if (12==length || 16==length || 18==length || 20==length) {
			return Pattern.matches(OTHER_ORGANIZATION_REGEX, socialCreditCode);
		}
		return false;
	}

	public static void main(String[] args) {
		System.out.println(isValidEntCode("331005590198123213你好","3"));
	}
}
